package util.netease;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import util.StringUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * @author shane
 * @version 1.0.0
 * @Date 2021/1/13 10:17
 */
public class Netease {
    /**
     * checkSum校验
     * @param app
     * @return
     * @throws Exception
     */
    public static Map<String, String> getHeaders(App app){
        Map<String, String> headers = new HashMap<>();

        String nonce = StringUtil.getRandomNumberStr(6);
        String curTime = System.currentTimeMillis()/1000+"";
        String value = app.getAppSecret()+nonce+curTime;

        //计算checkSum
        String checkSum = DigestUtil.sha1Hex(value).toLowerCase();

        headers.put("AppKey", app.getAppKey());
        headers.put("Nonce", nonce);
        headers.put("CurTime", curTime);
        headers.put("CheckSum", checkSum);
        return headers;
    }

    /**
     * post请求
     * @param url
     * @param params
     * @param app
     * @return
     */
    public static Map<String, Object> post(String url, Map<String, Object> params, App app){
        String result = HttpRequest.post(url)
                .addHeaders(Netease.getHeaders(app))
                .form(params)
                .execute().body();

        Map<String, Object> map = JSONObject.parseObject(result, Map.class);

        return map;
    }
}
